package service;


import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import dao.*;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.security.MessageDigest;
import util.*;

import form.YunjiaFaOwnForm;
import form.UserOwnForm;;

public class YunjiaService {
	private YunjiaDAO YunjiaDao;
	public static Logger log = Logger.getLogger(YunjiaService.class);

	
	public boolean yunjiaInsert(YunjiaFaOwnForm form,User user,int startAddressId,int endAddressId) {
		Address startAddress=new Address();
		Address endAddress=new Address();
		startAddress.setAddressid(startAddressId);
		endAddress.setAddressid(endAddressId);
		
		Calendar calendar = Calendar.getInstance();
		Date submitdate = calendar.getTime();
		String yunjiaCode=CodeCreate.createYunjiaCode(user.getUserid(), submitdate);
		String startAddr6=form.getStartAddress6();
		String endAddr6=form.getEndAddress6();
		String yunshuMode=form.getYunshuMode();
		
		int timecostDay=form.getTimecostDay();
		int timecostHour=form.getTimecostHour();
		String timecost=timecostDay+" 天 "+timecostHour+" 小时";
		String power=form.getShipPower();
		
		int validDay=form.getValidDay();
		calendar.add(Calendar.DATE, validDay);
		Date deadline=calendar.getTime();
		String yunjiaStatus="pending";
		String tejia=form.getTejia();
		
		String yunjiaInfo="";
		yunjiaInfo+="预报班次:"+form.getRegularTime()+"<br/>";
		//yunjiaInfo+="优惠:"+form.getDiscount()+"%<br/>";
		yunjiaInfo+="备注:"+form.getRemark()+"<br/>";
		
		int discount=form.getDiscount();
		int price1=form.getPrice1();
		String bizhong1=form.getBizhong1();
		String yunshuUnit1=form.getYunshuUnit1();
		int baseprice1=0;
		if(price1!=0)	baseprice1=(int)(price1*(1-0.01*discount));
		int price2=form.getPrice2();
		String bizhong2=form.getBizhong2();
		String yunshuUnit2=form.getYunshuUnit2();
		int baseprice2=0;
		if(price2!=0)	baseprice2=(int)(price2*(1-0.01*discount));
		int price3=form.getPrice3();
		String bizhong3=form.getBizhong3();
		String yunshuUnit3=form.getYunshuUnit3();
		int baseprice3=0;
		if(price3!=0)	baseprice3=(int)(price3*(1-0.01*discount));
		int price4=form.getPrice4();
		String bizhong4=form.getBizhong4();
		String yunshuUnit4=form.getYunshuUnit4();
		int baseprice4=0;
		if(price4!=0)	baseprice4=(int)(price4*(1-0.01*discount));
		int price5=form.getPrice5();
		String bizhong5=form.getBizhong5();
		String yunshuUnit5=form.getYunshuUnit5();
		int baseprice5=0;
		if(price5!=0)	baseprice5=(int)(price5*(1-0.01*discount));
		
		Yunjia yunjia=new Yunjia(startAddress,user,endAddress,yunjiaCode,startAddr6,endAddr6,
								yunshuMode,timecost,power,deadline,submitdate,yunjiaStatus,tejia,yunjiaInfo,
								price1,baseprice1,bizhong1,yunshuUnit1,price2,baseprice2,bizhong2,yunshuUnit2,
								price3,baseprice3,bizhong3,yunshuUnit3,price4,baseprice4,bizhong4,yunshuUnit4,
								price5,baseprice5,bizhong5,yunshuUnit5,null);
		YunjiaDao.save(yunjia);
		
		return true;
	}
	
	public boolean yunjiaDelete(int yunjiaid,User user) {
		Yunjia yunjia=YunjiaDao.findById(yunjiaid);
		//不是本人运价
		if(user.getUserid().intValue()!=yunjia.getUser().getUserid().intValue()) {
			return false;	
		}
		//不是 未通过 运价
		if(!yunjia.getYunjiastatus().toLowerCase().equals("deny")) {
			return false;
		}
		YunjiaDao.delete(yunjia);
		return true;
	}
	
	public List<Yunjia> yunjiaQuery(final String startAddress,final String endAddress,final Date startDate,final Date endDate, final User user,final int index) {
		List<Yunjia> yunjias=null;
		final String queryString;
		final int pageSize=PagingNum.PAGE_MAX;
		
//		final String sq,eq;
//		if(startAddressId==0) 	{sq="%";} 	
//		else 					{sq=""+startAddressId;}
//		if(endAddressId==0) 	{eq="%";} 	
//		else 					{eq=""+endAddressId;}

		if(!startAddress.equals("") || !endAddress.equals("")) {
			//queryString="from Yunjia as s where s.user.userid="+user.getUserid()+" and s.addressByStartaddressid.addressid like '"+sq+"' and s.addressByEndaddressid.addressid like '"+eq+"' order by submitdate desc";
			queryString="from Yunjia as s where s.user.userid="+user.getUserid()+" and s.addressByStartaddressid.level3cn like '%"+startAddress+"%' and s.addressByEndaddressid.level3cn like '%"+endAddress+"%' order by submitdate desc";
			yunjias=(List<Yunjia>)YunjiaDao.getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(final Session session)throws HibernateException{
					final Query query=session.createQuery(queryString);
					//query.setEntity(0, user);
					//query.setString(1, sq);
					//query.setString(2, eq);
					query.setFirstResult((index-1)*pageSize);
					query.setMaxResults(pageSize);
					return query.list();
				} 
			});
			
		} else {
			queryString="from Yunjia as s where s.user=? and s.submitdate >=? and s.submitdate<=?";

			yunjias=(List<Yunjia>)YunjiaDao.getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(Session session)throws HibernateException{
					Query query=session.createQuery(queryString);
					query.setEntity(0, user);
					query.setDate(1,startDate);
					query.setDate(2,endDate);
					query.setFirstResult((index-1)*pageSize);
					query.setMaxResults(pageSize);
					return query.list();
				} 
			});
		}
		
		return yunjias;
	}
	
	public PagingNum yunjiaNumQuery(String startAddress,String endAddress,Date startDate,Date endDate,User user,int index) {
		int pageSize=PagingNum.PAGE_MAX;
		PagingNum pagingNum=new PagingNum();
		int totalNum,approveNum,denyNum,pageNum;
		String queryString;
		List total,approve,deny;
		
		if(!startAddress.equals("") || !endAddress.equals("")) {
//			String sq,eq;
//			if(startAddressId==0) 	{sq="%";} 	
//			else 					{sq=""+startAddressId;}
//			if(endAddressId==0) 	{eq="%";} 	
//			else 					{eq=""+endAddressId;}
			
			queryString="select count(*) from Yunjia as s where s.user.userid="+user.getUserid()+" and s.addressByStartaddressid.level3cn like '%"+startAddress+"%' and s.addressByEndaddressid.level3cn like '%"+endAddress+"%'";
			//total=YunjiaDao.getHibernateTemplate().find(queryString,new Object[]{user,sq,eq});
			total=YunjiaDao.getHibernateTemplate().find(queryString);
			queryString="select count(*) from Yunjia as s where s.user.userid="+user.getUserid()+" and s.addressByStartaddressid.level3cn like '%"+startAddress+"%' and s.addressByEndaddressid.level3cn like '%"+endAddress+"%' and s.yunjiastatus='approved'";
			//approve=YunjiaDao.getHibernateTemplate().find(queryString,new Object[]{user,sq,eq});
			approve=YunjiaDao.getHibernateTemplate().find(queryString);
			queryString="select count(*) from Yunjia as s where s.user.userid="+user.getUserid()+" and s.addressByStartaddressid.level3cn like '%"+startAddress+"%' and s.addressByEndaddressid.level3cn like '%"+endAddress+"%' and s.yunjiastatus='deny'";
			//deny=YunjiaDao.getHibernateTemplate().find(queryString,new Object[]{user,sq,eq});
			deny=YunjiaDao.getHibernateTemplate().find(queryString);

		} else {
			queryString="select count(*) from Yunjia as s where s.user=? and"+" s.submitdate >=? and s.submitdate<=?";
			total=YunjiaDao.getHibernateTemplate().find(queryString,new Object[]{user,startDate,endDate});
			queryString="select count(*) from Yunjia as s where s.user=? and"+" s.submitdate >=? and s.submitdate<=? and s.yunjiastatus='approved'";
			approve=YunjiaDao.getHibernateTemplate().find(queryString,new Object[]{user,startDate,endDate});
			queryString="select count(*) from Yunjia as s where s.user=? and"+" s.submitdate >=? and s.submitdate<=? and s.yunjiastatus='deny'";
			deny=YunjiaDao.getHibernateTemplate().find(queryString,new Object[]{user,startDate,endDate});

		}
		if(null==total||total.size()==0||total.isEmpty()||null==total.get(0))
			totalNum=0;
		else
			totalNum=((Long)total.get(0)).intValue();
		if(null==approve||approve.size()==0||approve.isEmpty()||null==approve.get(0))
			approveNum=0;
		else
			approveNum=((Long)approve.get(0)).intValue();
		if(null==deny||deny.size()==0||deny.isEmpty()||null==deny.get(0))
			denyNum=0;
		else
			denyNum=((Long)deny.get(0)).intValue();
		
		pageNum=totalNum/pageSize;
		if(totalNum%pageSize!=0)	pageNum++;
			
		pagingNum.setPageIndex(index);
		pagingNum.setApproveNum(approveNum);
		pagingNum.setDenyNum(denyNum);
		pagingNum.setTotalNum(totalNum);
		pagingNum.setPageNum(pageNum);
		pagingNum.setStartDate(startDate.toString());
		pagingNum.setEndDate(endDate.toString());
		
		int a[]=new int[5];
		int i=0;
		if(index-2>0)	a[i++]=index-2;
		if(index-1>0)	a[i++]=index-1;
		a[i++]=index;
		if(index+1<=pageNum)	a[i++]=index+1;
		if(index+2<=pageNum)	a[i++]=index+2;
		pagingNum.setPageIndexes(a);
		
		return pagingNum;
	}

	public YunjiaDAO getYunjiaDao() {
		return YunjiaDao;
	}

	public void setYunjiaDao(YunjiaDAO yunjiaDao) {
		YunjiaDao = yunjiaDao;
	}
	
}